﻿using System.Collections.Generic;
using System.Linq;
using Dolany.UtilityTool;
using JetBrains.Annotations;
using Missbot.Core.Base;
using Missbot.Core.Cache;
using Missbot.Model.MsgCmds.Messaging;
using Missbot.Model.MsgInfos;
using Newtonsoft.Json;

namespace Missbot.Core.Channels
{
    [UsedImplicitly]
    public class MessagingMessageChannel : IMsgChannel
    {
        public override string Name => "messagingMessage";
        public override ChannelType BindingType => ChannelType.Messaging;
        public override string ChannelFlag => "messagingMessage";

        protected override void Send(OutboxDTO dto)
        {
            var cmd = dto.FileIDs.IsNullOrEmpty()
                          ? new CreateUserMessageCmd { UserID = dto.User.ID, Text = dto.Text }
                          : new CreateUserMessageWithFileCmd { UserID = dto.User.ID, Text = dto.Text, FileID = dto.FileIDs.First() };

            MsgSender.PushMsg(cmd);
        }

        public override void SendGroup(IEnumerable<InstanceUser> Users, InstanceGroup Group, string SourceID, string text, string file = null)
        {
            Send(new InboxSession { Group = Group, SourceID = SourceID }, text, file);
        }

        protected override InboxSession ParseDataImpl(string msg)
        {
            var model = JsonConvert.DeserializeObject<MessagingMessageInfo>(msg);
            if (model?.Body == null)
            {
                return null;
            }

            var body = model.Body.Body;
            if (body.GroupID != null)
            {
                return null;
            }

            return new InboxSession
            {
                Group = null,
                User = body.User,
                Text = body.Text,
                Files = body.File == null ? null : new[] { body.File },
                Channel = this,
                SourceID = body.ID
            };
        }
    }
}